/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.simulation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nudt.jCloud.infrastructure.Host;
import org.nudt.jCloud.workload.Task;

public class VirtSlotAlloc {
	private Framework frwk;
	private Map<Host, List<VirtSlot>> virtSlotSet;
	
	public VirtSlotAlloc(Framework frwk){
		setFrwk(frwk);
		virtSlotSet = new HashMap<Host, List<VirtSlot>>();
	}
	
	public void addVirtSlot(VirtSlot virtSlot){
		Host host = virtSlot.getHost();
		if(virtSlotSet.containsKey(host)){
			virtSlotSet.get(host).add(virtSlot);
		}else{
			virtSlotSet.put(host, new ArrayList<VirtSlot>());
			virtSlotSet.get(host).add(virtSlot);
		}
	}
	
	public void addVirtSlotList(List<VirtSlot> virtSlotList){
		for(int i=0; i<virtSlotList.size(); ++i){
			addVirtSlot(virtSlotList.get(i));
		}
	}
	
	public void removeVirtSlot(Task task){
		boolean removed = false;
		for(Host host : virtSlotSet.keySet()){
			List<VirtSlot> virtSlotList = virtSlotSet.get(host);
			for(VirtSlot virtSlot : virtSlotList){
				if(virtSlot.getTask()==task){
					removeVirtSlot(virtSlot);
					removed = true;
					break;
				}
			}
			if(removed == true){
				break;
			}
		}
		if(removed == false){
			throw new RuntimeException("cannot remove the virtual slot that assigned current task.");
		}
	}
	
	public void removeVirtSlot(VirtSlot virtSlot){
		Host host = virtSlot.getHost();
		if(virtSlotSet.containsKey(host)==false){
			throw new RuntimeException("cannot remove an un assigned virtual slot.");
		}else{
			virtSlotSet.get(host).remove(virtSlot);
			if(virtSlotSet.get(host).size()<=0){
				virtSlotSet.remove(host);
			}
		}
	}
	
	public boolean isEmpty(){
		if(virtSlotSet.size()==0){
			return true;
		}else{
			return false;
		}
	}

	public Framework getFrwk() {
		return frwk;
	}
	public void setFrwk(Framework frwk) {
		this.frwk = frwk;
	}
	public Map<Host, List<VirtSlot>> getVirtSlotSet() {
		return virtSlotSet;
	}
	public void setVirtSlotSet(Map<Host, List<VirtSlot>> virtSlotSet) {
		this.virtSlotSet = virtSlotSet;
	}

}
